package com.multition.demo01;

import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 该类是一个多例模式
 */
public class LingualResource {
    private String languageCode = "en";
    private String regionCode = "US";
    private String localeCode = "en_US";
    private static final String FILE_NAME = "res";

    // 存储的多个实例
    private static HashMap<String, LingualResource> instances = new HashMap(10);
    private Locale locale = null;
    private ResourceBundle resourceBundle = null;

    private LingualResource lnkLingualResource;

    private LingualResource(){
        //do nothing
    }

    private LingualResource(String languageCode, String regionCode) {
        this.languageCode = languageCode;
        this.regionCode = regionCode;
        localeCode = makeLocaleCode(languageCode , regionCode);

        locale = new Locale(languageCode, regionCode);

        resourceBundle = ResourceBundle.getBundle(FILE_NAME, locale);

        // zh_CN : resourceBundle
        instances.put( makeLocaleCode(languageCode, regionCode) , this);
    }

    public static synchronized LingualResource getInstance(String language, String region) {
        if (instances.containsKey(makeLocaleCode(language,region))) {
            return instances.get(makeLocaleCode(language, region));
        }
        return new LingualResource(language, region);
    }

    public String getLocaleString(String code) {
        return resourceBundle.getString(code);
    }

    private static String makeLocaleCode(String language, String region) {
        return language + "_" + region;
    }


}
